//
//  MapHomeViewController.m
//  DPProject
//
//  Created by 黄海明 on 2017/7/3.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import "MapHomeViewController.h"
#import "YYServiceParam.h"
#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#import "YYServiceManager.h"

// 填写你在鹰眼轨迹管理台创建的鹰眼服务对应的ID

@interface MapHomeViewController ()

@property (nonatomic, strong) BMKMapView *mapView;
/**
 使用点标注表示最新位置的坐标位置
 */
@property (nonatomic, strong) BMKPointAnnotation *locationPointAnnotation;
/**
 使用圆形覆盖物表示最新位置的定位精度
 */
@property (nonatomic, assign) BOOL serviceBasicInfoAlreadySetted;

@property (nonatomic, strong) BMKCircle *locationAccuracyCircle;
@property (nonatomic, strong) YYServiceParam *serviceBasicInfo;
@property (nonatomic, strong) NSTimer *timer;


@end

@implementation MapHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  self.view.backgroundColor = [UIColor whiteColor];
  [self.view addSubview:self.mapView];
  self.navigationController.navigationBarHidden=YES;
  [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];

  UIButton *bn=[[UIButton alloc]initWithFrame:CGRectMake(self.view.bounds.size.width-140, self.view.bounds.size.height-60, 85, 40)];
  [bn addTarget:self action:@selector(stateRequst) forControlEvents:UIControlEventTouchDown];
  [bn setTitle:@"开启服务" forState:UIControlStateNormal];
  [bn setBackgroundColor:[UIColor blueColor]];
  [self.view addSubview:bn];
  
  UIButton *bnAction=[[UIButton alloc]initWithFrame:CGRectMake(50, self.view.bounds.size.height-60, 85, 40)];
  [bnAction addTarget:self action:@selector(nameTest) forControlEvents:UIControlEventTouchDown];
  [bnAction setTitle:@"开始采集" forState:UIControlStateNormal];
  [bnAction setBackgroundColor:[UIColor blueColor]];
  [self.view addSubview:bnAction];
  
    // Do any additional setup after loading the view.
}



-(void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self.mapView viewWillAppear];
  self.mapView.delegate = self;
  [self resumeTimer];
  NSData *locationData = [USER_DEFAULTS objectForKey:LATEST_LOCATION];
  if (locationData) {
    CLLocation *position = [NSKeyedUnarchiver unarchiveObjectWithData:locationData];
    [self updateMapViewWithLocation:position];
  }
}

-(void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [self.mapView viewWillDisappear];
  self.mapView.delegate = nil;
  [self pauseTimer];
}

-(void)pauseTimer {
  [self.timer invalidate];
  self.timer = nil;
}

-(void)resumeTimer {
  if (self.timer) {
    [self.timer invalidate];
    self.timer = nil;
  }
  self.timer = [NSTimer scheduledTimerWithTimeInterval:self.serviceBasicInfo.gatherInterval target:self selector:@selector(queryLatestPosition) userInfo:nil repeats:YES];
}

-(NSTimer *)timer {
  if (_timer == nil) {
    _timer = [NSTimer timerWithTimeInterval:self.serviceBasicInfo.gatherInterval target:self selector:@selector(queryLatestPosition) userInfo:nil repeats:YES];
  }
  return _timer;
}

-(void)stateRequst{
  [self serviceButtonTapped];
}
-(void)nameTest{
  [self gatherButtonTapped];
}
#pragma mark - setter & getter
- (BMKMapView *)mapView {
  if (_mapView == nil) {
    CGFloat heightOfNavigationBar = self.navigationController.navigationBar.bounds.size.height;
    CGRect mapRect = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _mapView = [[BMKMapView alloc] initWithFrame:mapRect];
    _mapView.zoomLevel = 19;
  }
  return _mapView;
}

/**
 点击Service服务按钮触发的事件
 */
-(void)serviceButtonTapped {
  // 如果已经开启服务就停止服务；否则就开启服务
  if ([YYServiceManager defaultManager].isServiceStarted) {
    // 停止服务
    [[YYServiceManager defaultManager] stopService];
  } else {
    // 开启服务之间先配置轨迹服务的基础信息
    BTKServiceOption *basicInfoOption = [[BTKServiceOption alloc] initWithAK:AK mcode:MCODE serviceID:serviceID keepAlive:self.serviceBasicInfo.keepAlive];
    [[BTKAction sharedInstance] initInfo:basicInfoOption];
    // 开启服务
    BTKStartServiceOption *startServiceOption = [[BTKStartServiceOption alloc] initWithEntityName:self.serviceBasicInfo.entityName];
    [[YYServiceManager defaultManager] startServiceWithOption:startServiceOption];
  }
}
/**
 点击Gather采集按钮触发的事件
 */
-(void)gatherButtonTapped {
  // 如果已经开始采集就停止采集；否则就开始采集
  if ([YYServiceManager defaultManager].isGatherStarted) {
    // 停止采集
    [[YYServiceManager defaultManager] stopGather];
  } else {
    // 开始采集
    [[YYServiceManager defaultManager] startGather];
  }
}

-(instancetype)init {
  self = [super init];
  if (self) {
    _serviceBasicInfoAlreadySetted = FALSE;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serviceOperationResultHandler:) name:YYServiceOperationResultNotification object:nil];
  }
  return self;
}

/// 本方法查询实时位置，只是为了在轨迹服务的控制页面展示当前的位置，所以这里不设置纠偏选项。
/// 关于SDK中的queryTrackLatestPointWith方法，在其他页面中有详细介绍。
-(void)queryLatestPosition {
  dispatch_async(GLOBAL_QUEUE, ^{
    BTKQueryTrackLatestPointRequest *request = [[BTKQueryTrackLatestPointRequest alloc] initWithEntityName:self.serviceBasicInfo.entityName processOption:nil outputCootdType:BTK_COORDTYPE_BD09LL serviceID:serviceID tag:0];
    [[BTKTrackAction sharedInstance] queryTrackLatestPointWith:request delegate:self];
  });
}


-(YYServiceParam *)serviceBasicInfo {
  if (_serviceBasicInfo == nil) {
    _serviceBasicInfo = [[YYServiceParam alloc] init];
    // 配置默认值
    _serviceBasicInfo.gatherInterval = 5;
    _serviceBasicInfo.packInterval = 30;
    _serviceBasicInfo.activityType = CLActivityTypeAutomotiveNavigation;
    _serviceBasicInfo.desiredAccuracy = kCLLocationAccuracyBest;
    _serviceBasicInfo.distanceFilter = kCLDistanceFilterNone;
    _serviceBasicInfo.keepAlive = FALSE;
    NSString *entityName = [[NSUserDefaults standardUserDefaults] objectForKey:ENTITY_NAME];
    if (entityName != nil && entityName.length != 0) {
      _serviceBasicInfo.entityName = entityName;
    }
  }
  return _serviceBasicInfo;
}

#pragma mark - event response
-(void)serviceOperationResultHandler:(NSNotification *)notification {
  NSDictionary *info = notification.userInfo;
  ServiceOperationType type = (ServiceOperationType)[info[@"type"] unsignedIntValue];
  NSString *title = info[@"title"];
  NSString *message = info[@"message"];
  switch (type) {
    case YY_SERVICE_OPERATION_TYPE_START_SERVICE:
      [self showStartServiceResultWithTitle:title message:message];
      break;
    case YY_SERVICE_OPERATION_TYPE_STOP_SERVICE:
      [self showStopServiceResultWithTitle:title message:message];
      break;
    case YY_SERVICE_OPERATION_TYPE_START_GATHER:
      [self showStartGatherResultWithTitle:title message:message];
      break;
    case YY_SERVICE_OPERATION_TYPE_STOP_GATHER:
      [self showStopGatherResultWithTitle:title message:message];
      break;
    default:
      break;
  }
}
-(void)showStopGatherResultWithTitle:(NSString *)title message:(NSString *)message {
  dispatch_async(MAIN_QUEUE, ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//      [self updateGatherButtonStyle];
    }];
    [alertController addAction:defaultAction];
    if (self.presentedViewController == nil) {
      [self presentViewController:alertController animated:YES completion:nil];
    } else {
      [self dismissViewControllerAnimated:NO completion:^{
        dispatch_async(MAIN_QUEUE, ^{
          [self presentViewController:alertController animated:YES completion:nil];
        });
      }];
    }
  });
}
-(void)showStartGatherResultWithTitle:(NSString *)title message:(NSString *)message {
  dispatch_async(MAIN_QUEUE, ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//      [self updateGatherButtonStyle];
    }];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
  });
}

-(void)showStartServiceResultWithTitle:(NSString *)title message:(NSString *)message {
  dispatch_async(MAIN_QUEUE, ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      
    }];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
  });
}
-(void)showStopServiceResultWithTitle:(NSString *)title message:(NSString *)message {
  dispatch_async(MAIN_QUEUE, ^{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//      [self updateServiceButtonStyle];
    }];
    [alertController addAction:defaultAction];
    if (self.presentedViewController == nil) {
      [self presentViewController:alertController animated:YES completion:nil];
    } else {
      [self dismissViewControllerAnimated:YES completion:^{
        dispatch_async(MAIN_QUEUE, ^{
          [self presentViewController:alertController animated:YES completion:nil];
        });
      }];
    }
  });
}


#pragma mark - BMKMapViewDelegate
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
  if (annotation != self.locationPointAnnotation) {
    return nil;
  }
  static NSString * latestPointAnnotationViewID = @"latestPointAnnotationViewID";
  BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:latestPointAnnotationViewID];
  if (nil == annotationView) {
    annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:latestPointAnnotationViewID];
  }
  annotationView.image = [UIImage imageNamed:@"icon_center_point"];
  return annotationView;
}
-(BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay {
  if (FALSE == [overlay isMemberOfClass:[BMKCircle class]]) {
    return nil;
  }
  BMKCircleView *circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
  circleView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:0 alpha:0.3];
  circleView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0];
  return circleView;
}



-(void)onQueryTrackLatestPoint:(NSData *)response {
  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];
  if (nil == dict) {
    NSLog(@"Entity List查询格式转换出错");
    return;
  }
  if (0 != [dict[@"status"] intValue]) {
    NSLog(@"实时位置查询返回错误");
    return;
  }
  
  NSDictionary *latestPoint = dict[@"latest_point"];
  double latitude = [latestPoint[@"latitude"] doubleValue];
  double longitude = [latestPoint[@"longitude"] doubleValue];
  CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
  double horizontalAccuracy = [latestPoint[@"radius"] doubleValue];
  double loctime = [latestPoint[@"loc_time"] doubleValue];
  NSDate *timestamp = [NSDate dateWithTimeIntervalSince1970:loctime];
  CLLocation *latestLocation = [[CLLocation alloc] initWithCoordinate:coordinate altitude:0 horizontalAccuracy:horizontalAccuracy verticalAccuracy:0 timestamp:timestamp];
  // 存储最新的实时位置只是为了在地图底图一开始加载的时候，以上一次最新的实时位置作为底图的中心点
  [USER_DEFAULTS setObject:[NSKeyedArchiver archivedDataWithRootObject:latestLocation] forKey:LATEST_LOCATION];
  [USER_DEFAULTS synchronize];
  [self updateMapViewWithLocation:latestLocation];
}


-(void)updateMapViewWithLocation:(CLLocation *)latestLocation {
  CLLocationCoordinate2D centerCoordinate = latestLocation.coordinate;
  // 原点代表最新位置
  dispatch_async(MAIN_QUEUE, ^{
    self.locationPointAnnotation.coordinate = centerCoordinate;
    self.locationPointAnnotation.title = self.serviceBasicInfo.entityName;
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView addAnnotation:self.locationPointAnnotation];
  });
  
  // 填充圆代表定位精度
  dispatch_async(MAIN_QUEUE, ^{
    self.locationAccuracyCircle.coordinate = centerCoordinate;
    self.locationAccuracyCircle.radius = latestLocation.horizontalAccuracy;
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapView addOverlay:self.locationAccuracyCircle];
  });
  
  // 移动地图中心点
  dispatch_async(MAIN_QUEUE, ^{
    [self.mapView setCenterCoordinate:centerCoordinate animated:TRUE];
  });
}
-(BMKPointAnnotation *)locationPointAnnotation {
  if (_locationPointAnnotation == nil) {
    _locationPointAnnotation = [[BMKPointAnnotation alloc] init];
  }
  return _locationPointAnnotation;
}
-(BMKCircle *)locationAccuracyCircle {
  if (_locationAccuracyCircle == nil) {
    _locationAccuracyCircle = [[BMKCircle alloc] init];
  }
  return _locationAccuracyCircle;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
